package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.UserFreezeApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private UserFreezeApi userFreezeApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 远程调用dubbo服务，返回mybatis-plus的分页对象
        IPage<UserInfo> iPage = userInfoApi.findByPage(page, pagesize);

        //  ----xz添加的代码
        //有可能用户冻结的时间已结束，但是查到的UserInfo还没更新冻结状态，所以显示用户翻页列表时要做冻结结束时间的判断然后更新冻结状态
        List<UserInfo> userInfoList = iPage.getRecords();
        for (UserInfo userInfo : userInfoList) {
            Long userId = userInfo.getId();
            //如果用户状态为冻结状态，此时有可能用户冻结的终止时间其实已经到了，通过当前时间与用户冻结终止时间进行比较，判断是否已结束冻结
            if (userInfo.getUserStatus().equals("2")) {
                //1.从redis缓存中获取冻结终止时间
                String thawingTimeStr = redisTemplate.opsForValue().get("user_freeze_" + userId);
                if (thawingTimeStr == null) {
                    //如果获取不到冻结终止时间，说明是永久冻结，就让它继续保持冻结，不进行状态修改
                    continue;
                }
                Long thawingTime = Long.valueOf(thawingTimeStr);
                //2.与当前时间作比较
                if (System.currentTimeMillis() > thawingTime) {
                    //如果当前时间毫秒值大于冻结终止时间的毫秒值，就说明用户已经解冻，要把用户的冻结状态改回正常状态
                    //修改用户在tb_user_info表里的user_status值，改成1(正常状态)
                    userInfo.setUserStatus("1");
                    userInfoApi.update(userInfo);
                    //删除mongo中user_freeze表的数据
                    userFreezeApi.delete(userId);
                    //删除redis中冻结终止时间的缓存数据
                    redisTemplate.delete("user_freeze_" + userId);
                }
            }
        }

        // 构造返回给前端的分页数据
        PageResult pageResult =
                new PageResult(page, pagesize, (int) iPage.getTotal(), userInfoList);//----此处改成userInfoList
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户基本资料
     */
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 接口名称：视频记录翻页
     */
    public ResponseEntity<Object> findVideoList(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult = videoApi.findByPage(page, pagesize, uid);
        List<Video> videoList = (List<Video>) pageResult.getItems();

        //2、创建返回的vo集合对象
        List<VideoVo> voList = new ArrayList<>();

        //3. 封装数据
        if (videoList != null) {
            for (Video video : videoList) {
                //3.1 创建vo对象，封装前端返回的数据
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(video, vo);
                //3.2 根据用户id查询用户并封装
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                //3.3 设置小视频封面
                vo.setCover(video.getPicUrl());
                //3.4 设置id、签名
                vo.setId(video.getId().toString());
                vo.setSignature(video.getText());
                vo.setHasLiked(0);

                //3.5 vo添加到集合
                voList.add(vo);
            }
        }
        //4. 设置到PageResult中
        pageResult.setItems(voList);

        //5. 响应
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> findMovementsList(
            Integer page, Integer pagesize, Long uid, String state) {
        PageResult pageResult = publishApi.queryPublishList(page, pagesize, uid, state);
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        //3. 封装返回的结果MovementsVo集合
        //3.1 创建返回结果
        List<MovementsVo> voList = new ArrayList<>();
        //3.2 遍历查询的发布动态集合
        if (publishList != null) {
            for (Publish publish : publishList) {
                //3.2.1 创建vo对象
                MovementsVo vo = new MovementsVo();
                //3.2.2 封装数据：发布动态
                BeanUtils.copyProperties(publish, vo);
                //3.2.3 封装数据：先查询用户详情，再封装
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                    if (userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                //3.2.3 封装数据：其他参数
                vo.setId(publish.getId().toString());
                vo.setUserId(publish.getUserId());
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                vo.setDistance("50米");
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

                //封装审核状态    ----xz添加的代码
                if (publish.getState() == 0) {
                    vo.setState("1");
                } else if (publish.getState() == 1) {
                    vo.setState("2");
                } else {
                    vo.setState("6");
                }

                //3.2.4 对象添加到集合
                voList.add(vo);
            }
        }

        //4. 在把封装好的vo集合设置到分页对象中
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        Publish publish = publishApi.findById(publishId);

        //3.2.1 创建vo对象
        MovementsVo vo = new MovementsVo();
        //3.2.2 封装数据：发布动态
        BeanUtils.copyProperties(publish, vo);
        //3.2.3 封装数据：先查询用户详情，再封装
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        //3.2.3 封装数据：其他参数
        vo.setId(publish.getId().toString());
        vo.setUserId(publish.getUserId());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setDistance("50米");
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

        //封装审核状态    ----xz添加的代码
        if (publish.getState() == 0) {
            vo.setState("1");
        } else if (publish.getState() == 1) {
            vo.setState("2");
        } else {
            vo.setState("6");
        }

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        //1. 根据动态id分页查询评论
        PageResult pageResult = commentApi.queryCommentsList(publishId, page, pagesize);

        //2. 获取查询数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        //3. 创建返回的vo集合数据
        List<CommentVo> voList = new ArrayList<>();

        //4. 封装voList
        if (commentList != null) {
            for (Comment comment : commentList) {
                CommentVo vo = new CommentVo();
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                vo.setId(comment.getId().toString());

                vo.setContent(comment.getContent());
                vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                vo.setLikeCount(0);
                vo.setHasLiked(0);

                voList.add(vo);
            }
        }

        //5. 设置到分页对象中并返回
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户冻结操作
     */
    public ResponseEntity<Object> userFreeze(UserFreeze userFreeze) {
        //1.修改冻结用户在tb_user_info表中的userStatus状态为2，表示冻结
        // 先得到冻结用户的id对应的UserInfo对象
        UserInfo userInfo = userInfoApi.findById(userFreeze.getUserId().longValue());
        // 修改UserInfo对象的userStatus为2
        userInfo.setUserStatus("2");
        //更新数据到数据库
        userInfoApi.update(userInfo);

        //2.往mongo的user_freeze表中插入数据
        userFreezeApi.save(userFreeze);

        //3.把冻结的终止时间记录到redis中
        if (userFreeze.getFreezingTime() == 1) {
            Long thawingTime = System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000;
            redisTemplate.opsForValue().set("user_freeze_" + userFreeze.getUserId(), thawingTime.toString());
        } else if (userFreeze.getFreezingTime() == 2) {
            Long thawingTime = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000;
            redisTemplate.opsForValue().set("user_freeze_" + userFreeze.getUserId(), thawingTime.toString());
        }

        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：用户解冻操作
     */
    public ResponseEntity<Object> userUnfreeze(Long userId) {
        //1.修改解冻用户在tb_user_info表中的userStatus状态为1，表示解冻
        // 先得到冻结用户的id对应的UserInfo对象
        UserInfo userInfo = userInfoApi.findById(userId);
        // 修改UserInfo对象的userStatus为1
        userInfo.setUserStatus("1");
        //更新数据到数据库
        userInfoApi.update(userInfo);

        //2.删除mongo的user_freeze表中的冻结数据并删除redis中的冻结终止时间的缓存数据
        userFreezeApi.delete(userId);
        redisTemplate.delete("user_freeze_" + userId);

        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：动态通过
     */
    public ResponseEntity<Object> pass(List<String> publishIdList) {
        //遍历publishIdList，修改对应punlishId的动态的state变为1
        if (publishIdList != null && publishIdList.size() > 0) {
            for (String publishId : publishIdList) {
                publishApi.updateState(publishId, 1);
            }
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：动态拒绝
     */
    public ResponseEntity<Object> reject(List<String> publishIdList) {
        //遍历publishIdList，修改对应punlishId的动态的state变为2
        if (publishIdList != null && publishIdList.size() > 0) {
            for (String publishId : publishIdList) {
                publishApi.updateState(publishId, 2);
            }
        }
        return ResponseEntity.ok(null);
    }
}
